#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
 Jexjex
 Copyright Jan-Karel Visser - all rights are reserved
 Licensed under the LGPL v3

 This program is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

"""


class Cdn_Model:

    def __init__(self, jexjex):
        self.app = jexjex

    def get(self):
        return self.app.db((self.jexjex_cdn.id == self.app.request.arg(1)) & \
                           (self.jexjex_cdn.soort == 'image')).select(\
                            self.jexjex_cdn.soort, self.jexjex_cdn.rel,
                            self.jexjex_cdn.name, self.jexjex_cdn.filename,
                         self.jexjex_cdn.source, self.jexjex_cdn.soort).first()

    def serve_file(self):
        rw = self.app.db((self.jexjex_cdn.filename == self.app.request.arg(1))\
                           & (self.jexjex_cdn.rel == 'local')).select(\
                        self.jexjex_cdn.mime, self.jexjex_cdn.uploaded).first()
        if rw:
            self.app.headers = [('Cache-Control', 'public, max-age=290304000'),
                                ('Content-type', rw.mime),
                                ('Content-Length', str(len(rw.uploaded)))]
            return rw.uploaded
        else:
            return False

    def files(self, soort='image'):
        g = ''
        row = self.app.db(self.jexjex_cdn.soort == soort).select(\
              self.jexjex_cdn.name, self.jexjex_cdn.id, self.jexjex_cdn.source)
        for x in row:
            g += g + '<figure><img src="' + x.source + '" alt="' + x.name + '"\
                  /><figcaption><a href="#">' + x.name + '</a> <a rel="'\
                  + str(x.id) + '" class="pull-right figure-verwijder \
                  icon-trash">delete</a></figcaption></figure>'
        return g

    def create_models(self):
  #cdn - handles images and files
        if not hasattr(self.app.db, 'jexjex_cdn'):
            self.jexjex_cdn = self.app.db.define_table("jexjex_cdn",
                        self.app.field("name", 'string'),
                        self.app.field("filename", 'string'),
                        self.app.field("soort", 'string'),
                        self.app.field("mime", 'string'),
                        self.app.field("source", 'string'),
                        self.app.field("rel", 'string'),
                        self.app.field("size", 'string'),
                        self.app.field("via", 'string'),
                        self.app.field("datum", 'datetime', \
                                                 default=self.app.request.now),
                        self.app.field("uploaded", 'blob')
                        )
        else:
            self.jexjex_cdn = self.app.db.jexjex_cdn
